package com.bit.dreamer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import javax.security.auth.Destroyable;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class DreamMap extends Activity implements OnTouchListener {
	DreamHelper helper;
	SQLiteDatabase db;
	Cursor rs;
	ArrayList<ListContent> mapArray;
	Bitmap bm;
	ImageView iv;
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();
	private Matrix savedMatrix2 = new Matrix();

	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;

	private static final int WIDTH = 0;
	private static final int HEIGHT = 1;

	// Remember some things for zooming
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	
	ImageView myImg;
	Button imgSave;
	SharedPreferences sf;
	Uri uri;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dream_map);
		
		ActionBar actionbar = getActionBar();
		actionbar.hide();
		
		iv = (ImageView)findViewById(R.id.imageView);
		myImg = (ImageView)findViewById(R.id.myImg);
		imgSave = (Button)findViewById(R.id.imgSave);
		
		mapArray = new ArrayList<ListContent>();
		
		helper = new DreamHelper(this);
		iv.setOnTouchListener(this);
		uri = Uri.parse("1");
        selecter("SELECT dreamdate, img FROM D_become_tb ORDER BY dreamdate  ASC LIMIT 5");
        selecter("SELECT dreamdate, img FROM D_have_tb ORDER BY dreamdate  ASC LIMIT 5");
        selecter("SELECT dreamdate, img FROM D_do_tb ORDER BY dreamdate  ASC LIMIT 4"); 

		drawMap();
		
		iv.setImageBitmap(bm);
		myImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
				intent.setType("image/*");	
				try {
					startActivityForResult(intent, 101);
				}catch(Exception e) {}
			}
		});
		
		imgSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SharedPreferences.Editor editor = sf.edit();
				editor.putString("myImg", uri.toString());
				editor.commit();
				if(uri.toString().equals("1")) {
					Toast.makeText(getApplicationContext(), "사진을 지정하세요", 1000).show();
				}
				Toast.makeText(getApplicationContext(), "3초 기달려 주세요", 1000).show();
				recreate();
			}
		});
		
	}//onCreate
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if(requestCode == 101 && resultCode == RESULT_OK) {
			uri = data.getData();
			sizeChange(uri);
		}
	}


	private void sizeChange(Uri uri) {
		Bitmap bitmap;
		Bitmap resized = null;
		try {
			bitmap = Images.Media.getBitmap(getContentResolver(), uri);
			int height = bitmap.getHeight();
			int width = bitmap.getWidth();
			if(height > 2048) {
				while (height > 2048) {
					resized = Bitmap.createScaledBitmap(bitmap, (width * 2048) / height, 2048, true);
					height = resized.getHeight();
					width = resized.getWidth();
					myImg.setImageBitmap(resized);
				}
			} else {
				myImg.setImageBitmap(bitmap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void selecter(String query) {
		db = helper.getReadableDatabase();
		rs = db.rawQuery(query, null);
		while (rs.moveToNext()) {
//			byte[] b = rs.getBlob(1);
			mapArray.add(new ListContent(rs.getString(0), rs.getString(1), ""));
		}//while
		rs.close();
		helper.close();
	} 
			
			
			
			
			//			switch (sel) {
//			case 1:
//				mapArray_become.add(new ListContent(BitmapFactory.decodeByteArray(b , 0 , b.length), rs.getString(0)));
//				break;
//			case 2:
//				mapArray_have.add(new ListContent(BitmapFactory.decodeByteArray(b , 0 , b.length), rs.getString(0)));
//				break;
//			case 3:
//				mapArray_do.add(new ListContent(BitmapFactory.decodeByteArray(b , 0 , b.length), rs.getString(0)));
//				break;
//			}
			
//			i++;
//		}//while
//	}
	
	@SuppressWarnings("deprecation")
	private void drawMap() {
		Paint paint = new Paint();
		paint.setColor(Color.BLACK);
		paint.setTextSize(50);
		paint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));

		WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		
		Log.d("weight", display.getWidth() + "");
		Log.d("height", display.getHeight() + "");
		
		float dWidth = display.getWidth() * 2;
		float dHeight = display.getHeight() * 2;
		float cWidth = display.getWidth();
		float cHeight = display.getHeight();
		
		Log.d("weight", dWidth+ "");
		Log.d("height", dHeight + "");
		
//		bm = Bitmap.createBitmap(display.getWidth() , display.getHeight(), Bitmap.Config.ARGB_8888);
		bm = Bitmap.createBitmap(display.getWidth() * 2 , display.getHeight() * 2, Bitmap.Config.ARGB_8888);
		
		Canvas screen = new Canvas(bm);
//		screen.drawColor(Color.LTGRAY);
		
        Resources res = getResources();
        BitmapDrawable bd = (BitmapDrawable)res.getDrawable(R.drawable.chipan);
        Bitmap bitmap = bd.getBitmap();
        screen.drawBitmap(bitmap, null, new RectF(0, 0, dWidth, dHeight),  null); 

        //        paint.setTextSize(200);
//        screen.drawText("공사중입니다..", cWidth / 2, cHeight / 2, paint);
        
		sf = getSharedPreferences("myImg", MODE_PRIVATE);
		uri = Uri.parse(sf.getString("myImg", ""));
		sizeChange(uri);
		
//		myImg.setImageURI(uri);
		
//		Bitmap resized = null;
//		try {
//			Bitmap bitmap3 = Images.Media.getBitmap(getContentResolver(), uri);
//			int height = bitmap3.getHeight();
//			int width = bitmap3.getWidth();
//			if(height > 2048) {
//				while (height > 2048) {
//					resized = Bitmap.createScaledBitmap(bitmap3, (width * 2048) / height, 2048, true);
//					height = resized.getHeight();
//					width = resized.getWidth();
//					myImg.setImageBitmap(resized);
//				}
//			} else {
//				myImg.setImageBitmap(bitmap3);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		
		
		
		bd = (BitmapDrawable)res.getDrawable(R.drawable.smile2);
		Bitmap bitmap2 = bd.getBitmap();
		try {
			 bitmap2 = Images.Media.getBitmap(getContentResolver(), uri);
//			 bitmap2 = Bitmap.createScaledBitmap(bitmap2, 100, 100, true);
		} catch(Exception e) {}
       
		screen.drawBitmap(bitmap2, null, new RectF(cWidth - (cWidth * 0.16f), cHeight - (cHeight * 0.31f), cWidth + (cWidth * 0.16f), cHeight + (cHeight * 0.28f)),  null);
		
	    bd = (BitmapDrawable)res.getDrawable(R.drawable.poit2);
        bitmap = bd.getBitmap();

        int num = 0;
		float sX = dWidth * 0.03f, eX = dWidth * 0.15f, sY = dHeight * 0.05f, eY = dHeight * 0.25f;

		for(int i = 0; i < 3; i++) {
			if(i >= mapArray.size())
				break;
			num++;
			try {
				Bitmap dbbit = Images.Media.getBitmap(getContentResolver(), Uri.parse(mapArray.get(i).uri));
				screen.drawBitmap(bitmap, null, new RectF(sX - (dWidth * 0.015f), sY - (dHeight * 0.032f), eX + (dWidth * 0.025f), eY + (dHeight * 0.09f)),  null);
				screen.drawBitmap(dbbit, null, new RectF(sX, sY, eX, eY),  null);
				screen.drawText(mapArray.get(i).dreamdate, sX + (dWidth * 0.015f), sY + (dHeight * 0.24f), paint);
			} catch (Exception e) {e.printStackTrace();}

			
			sY += dHeight * 0.31;
			eY += dHeight * 0.31;
		}
		
		sX += dWidth * 0.16f;
		eX += dWidth * 0.16f;
		sY -= dHeight * 0.31f;
		eY -= dHeight * 0.31f;

		for(int i = num; i < 8; i++) {
			if(i >= mapArray.size())
				break;
			num++;
			try {
				Bitmap dbbit = Images.Media.getBitmap(getContentResolver(), Uri.parse(mapArray.get(i).uri));
				screen.drawBitmap(bitmap, null, new RectF(sX - (dWidth * 0.015f), sY - (dHeight * 0.032f), eX + (dWidth * 0.025f), eY + (dHeight * 0.09f)),  null);
				screen.drawBitmap(dbbit, null, new RectF(sX, sY, eX, eY),  null);
				screen.drawText(mapArray.get(i).dreamdate, sX + (dWidth * 0.015f), sY + (dHeight * 0.24f), paint);
			} catch (Exception e) {e.printStackTrace();}

			sX += dWidth * 0.16f;
			eX += dWidth * 0.16f;
		}
		
		sX -= dWidth * 0.16f;
		eX -= dWidth * 0.16f;
		sY -= dHeight * 0.31f;
		eY -= dHeight * 0.31f;
		
		for(int i = num; i < 10; i++) {
			if(i >= mapArray.size())
				break;
			num++;
			try {
				Bitmap dbbit = Images.Media.getBitmap(getContentResolver(), Uri.parse(mapArray.get(i).uri));
				screen.drawBitmap(bitmap, null, new RectF(sX - (dWidth * 0.015f), sY - (dHeight * 0.032f), eX + (dWidth * 0.025f), eY + (dHeight * 0.09f)),  null);
				screen.drawBitmap(dbbit, null, new RectF(sX, sY, eX, eY),  null);
				screen.drawText(mapArray.get(i).dreamdate, sX + (dWidth * 0.015f), sY + (dHeight * 0.24f), paint);
			} catch (Exception e) {e.printStackTrace();}

			sY -= dHeight * 0.31f;
			eY -= dHeight * 0.31f;
		}
		sX -= dWidth * 0.16f;
		eX -= dWidth * 0.16f;
		sY += dHeight * 0.31f;
		eY += dHeight * 0.31f;
		for(int i = num; i < 14; i++) {
			if(i >= mapArray.size())
				break;
			num++;
			try {
				Bitmap dbbit = Images.Media.getBitmap(getContentResolver(), Uri.parse(mapArray.get(i).uri));
				screen.drawBitmap(bitmap, null, new RectF(sX - (dWidth * 0.015f), sY - (dHeight * 0.032f), eX + (dWidth * 0.025f), eY + (dHeight * 0.09f)),  null);
				screen.drawBitmap(dbbit, null, new RectF(sX, sY, eX, eY),  null);
				screen.drawText(mapArray.get(i).dreamdate, sX + (dWidth * 0.015f), sY + (dHeight * 0.24f), paint);
			} catch (Exception e) {e.printStackTrace();}

			sX -= dWidth * 0.16f;
			eX -= dWidth * 0.16f;
		}
		
	}//drawMap
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {

		// MotionEvent.ACTION_MASK : 터치 이벤트 액션을 구분짓기 위한 MASK
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			if (oldDist > 10f) {
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) {
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
			} else if (mode == ZOOM) {
				float newDist = spacing(event);
				if (newDist > 10f) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}

		matrixTurning(matrix, iv);
		iv.setImageMatrix(matrix);
		return true; 
	}//onTouch

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}//spacing

	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}//midPoint


	private void matrixTurning(Matrix matrix, ImageView view){
		// 매트릭스 값
		float[] value = new float[9];
		matrix.getValues(value);
		float[] savedValue = new float[9];
		savedMatrix2.getValues(savedValue);

		// 뷰 크기
		int width = view.getWidth();
		int height = view.getHeight();

		// 이미지 크기
		Drawable d = view.getDrawable();
		if (d == null)  return;
		int imageWidth = d.getIntrinsicWidth();
		int imageHeight = d.getIntrinsicHeight();
		int scaleWidth = (int) (imageWidth * value[0]);
		int scaleHeight = (int) (imageHeight * value[4]);

		// 이미지가 바깥으로 나가지 않도록.
		if (value[2] < width - scaleWidth)   value[2] = width - scaleWidth;
		if (value[5] < height - scaleHeight)   value[5] = height - scaleHeight;
		if (value[2] > 0)   value[2] = 0;
		if (value[5] > 0)   value[5] = 0;

		// X배 이상 확대 하지 않도록
		if (value[0] > 3 || value[4] > 3){
			value[0] = savedValue[0];
			value[4] = savedValue[4];
			value[2] = savedValue[2];
			value[5] = savedValue[5];
		}

		// 화면보다 작게 축소 하지 않도록
		if (imageWidth > width || imageHeight > height){
			if (scaleWidth < width && scaleHeight < height){
				int target = WIDTH;
				if (imageWidth < imageHeight) target = HEIGHT;

				if (target == WIDTH) value[0] = value[4] = (float)width / imageWidth;
				if (target == HEIGHT) value[0] = value[4] = (float)height / imageHeight;

				scaleWidth = (int) (imageWidth * value[0]);
				scaleHeight = (int) (imageHeight * value[4]);

				if (scaleWidth > width) value[0] = value[4] = (float)width / imageWidth;
				if (scaleHeight > height) value[0] = value[4] = (float)height / imageHeight;
			}
		}

		//  원래부터 작은 얘들은 본래 크기보다 작게 하지 않도록
		else{
			if (value[0] < 1)   value[0] = 1;
			if (value[4] < 1)   value[4] = 1;
		}

		// 그리고 가운데 위치하도록 한다.
		scaleWidth = (int) (imageWidth * value[0]);
		scaleHeight = (int) (imageHeight * value[4]);
		if (scaleWidth < width){
			value[2] = (float) width / 2 - (float)scaleWidth / 2;
		}
		if (scaleHeight < height){
			value[5] = (float) height / 2 - (float)scaleHeight / 2;
		}

		matrix.setValues(value);
		savedMatrix2.set(matrix);
	}//matrixTurning

	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.lotto_main, menu);
//		return true;
		
		super.onCreateOptionsMenu(menu);
		
		MenuItem item = menu.add(0, 1, 0, "로그인");
		item.setIcon(R.drawable.ic_launcher);
		item.setAlphabeticShortcut('a'); // 키보드 a를 누르면 실행되게끔
		
		menu.add(0, 2, 0, "꿈등록");
		menu.add(0, 3, 0, "꿈목록");
		menu.add(0, 5, 0, "메뉴들");
		
	return true;
	}//onCreateOptionsMenu
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch ( item.getItemId()){
		case 1:
			Intent intent1= new Intent(getApplicationContext(), MainActivity.class);
			startActivity(intent1);
			
			Toast.makeText(this, "로그인 화면 가기", Toast.LENGTH_SHORT).show();
			return true;

		case 2 :
			Intent intent2= new Intent(getApplicationContext(), MainMenuActivity.class);
			startActivity(intent2);
			Toast.makeText(this, "나의 꿈 목록 보기", Toast.LENGTH_SHORT).show();
			return true;

		case 3 :
			Intent intent3= new Intent(getApplicationContext(), DreaminsertActivity.class);
			startActivity(intent3);

			Toast.makeText(this, "나의 꿈 등록 하기", Toast.LENGTH_SHORT).show();
			return true;

		case 5 :
			Intent intent5= new Intent(getApplicationContext(), com.bit.dreamer.SubMenu.class);
			startActivity(intent5);

			Toast.makeText(this, "다양한 메뉴들 보기", Toast.LENGTH_SHORT).show();
			return true;

		}
		return false;

	}//onOptionsItemSelected

	
}
